/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.action.retrievedefault;

import com.inspur.edp.bef.api.be.IBusinessEntity;
import com.inspur.edp.bef.core.DotNetToJavaStringHelper;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.bef.spi.entity.builtinimpls.BefEntityResInfoImpl;
import com.inspur.edp.bef.spi.entity.columnconfig.ColumnGenerateConfigLoader;
import com.inspur.edp.bef.spi.entity.columnconfig.ColumnGenerateInfo;
import com.inspur.edp.cef.api.rootManager.ICefRootManager;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.spi.entity.resourceInfo.EntityResInfo;
import java.util.UUID;

public class CreateChildDataMgrAction extends AbstractManagerAction<IEntityData> {
  private ICefRootManager manager;
  private String childCode;
  private boolean useID;
  private String dataID;

  public CreateChildDataMgrAction(
      ICefRootManager manager, String childCode, boolean useID, String dataID) {
    this.manager = manager;
    this.childCode = childCode;
    this.useID = useID;
    this.dataID = dataID;
  }

  private String getID() {
    if (DotNetToJavaStringHelper.isNullOrEmpty(dataID) == false) {
      return dataID;
    }
    return getColumnId();
  }

  @Override
  public void execute() {
IBusinessEntity entity =
        (IBusinessEntity) manager.createSessionlessEntity(UUID.randomUUID().toString());
    setResult(entity.createChildData(childCode, getID()));
  }


  private String getColumnId(){
    EntityResInfo resInfo;
    try {
      resInfo=this.getBEManagerContext().getModelResInfo().getCustomResource(childCode);
    }catch (Exception e){
      return UUID.randomUUID().toString();
    }
    if(resInfo==null)
      return UUID.randomUUID().toString();
    if(!(resInfo instanceof BefEntityResInfoImpl))
      return  UUID.randomUUID().toString();
    ColumnGenerateInfo columnGenerateInfo=((BefEntityResInfoImpl)resInfo).getColumnGenerateInfo();
    return ColumnGenerateConfigLoader.getId(columnGenerateInfo);
  }
}
